//#include "HD61202.h"
#include "shared.h"
#include "serial.h"
#include "buffers.h"
#include "strings.h"
#include "string.h"

// note: contents of sendBuffer may not be null-terminated.
#pragma udata screen
// not always used as a frame buffer
volatile unsigned char lcdBuffer[lcdBufSize];
#pragma udata
volatile unsigned int lcdBufIndex = 0;
volatile unsigned char sendBuffer[sendBufSize],	sendIndex = 0, sendCount = 0,
// use receiveBuffer for commands only, not data
	receiveBuffer[rcBufSize], rcBufHead = 0, rcBufTail = 0;

char receiveBufIns(unsigned char data){
	char rcBufFree;
	unsigned char 	nextRcBufHead = rcBufHead + 1,
					tempChar[5];
	static unsigned char fullSent = 0;
	if(nextRcBufHead >= rcBufSize) nextRcBufHead = 0;
	if(nextRcBufHead == rcBufTail){ // buffer full
		if(!fullSent){
			strcpypgm2ram(tempChar, bufferFull);
//			putrsUSARTInt(bufferFull, strlenpgm(bufferFull));
			putsUSARTInt(tempChar);
			fullSent = 1;
		}
		return -1;
	}
	receiveBuffer[rcBufHead] = data;
	rcBufHead = nextRcBufHead;
	rcBufFree = rcBufTail - rcBufHead;
	if(rcBufFree <= 0) rcBufFree += rcBufSize;
	if(rcBufFree <= rcBufSize >> 2)
		return 1;
	else
		return 0;
}

unsigned char receiveBufRem(){
	unsigned char tmpChar = receiveBuffer[rcBufTail++];
	if(rcBufTail >= rcBufSize) rcBufTail = 0;
#ifdef useFlowControl
	if(rcBufTail == rcBufHead && XOFFsent){
		putcUSARTInt(XON);
		XOFFsent = 0;
	}
#endif
	return tmpChar;
}

void receiveBufRedirect(char * dest, int len){
	int i;
	for(i = 0; i < len; i++){
		while(rcBufHead == rcBufTail);
		dest[i] = receiveBufRem();
	}
}

